package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {


    @Override
    public ResponseResult<WmChannel> listByName(ChannelDto dto) {
        //根据名称分页查询
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //使用mybatisplus推荐的lamda表达式的写法
        //LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(dto.getName())) {
            //构建name模糊查询
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        //构建分页对象
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        //返回查询结果
        IPage<WmChannel> page1 = this.page(page, queryWrapper);
        //构建分页结果对象
        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult saveWmChannel(WmChannel wmChannel) {

        //wmChannel不能为空
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }


        //判断这个频道是否存在
        //先查询
        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(WmChannel::getName, wmChannel.getName());

        WmChannel one = this.getOne(queryWrapper);

        if (one != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        wmChannel.setCreatedTime(new Date());
        this.save(wmChannel);
        return ResponseResult.okResult();
    }
}
